package com.icast.interlayer;

import android.media.MediaPlayer;
import android.media.MediaPlayer.OnPreparedListener;
import android.view.SurfaceHolder;
import android.view.SurfaceView;

import com.icast.api.ICast;
import com.icast.tools.LogCat;
import com.icast.ui.MainActivity;
import com.smit.player.SmitPlayer;

/**
 * 本类中的方法由iCastApi调用，具体内容需应用端实现
 * 
 * @author yuchen
 */
public class Interlayer {

	/**************************************** UI操作 ****************************************/

	/**
	 * 输出打印信息
	 * 
	 * @param log
	 *            打印信息，单行最多100字符，可折行
	 */
	public static void log(String log) {
		MainActivity.log(log);
	}

	/**
	 * 搜台结束
	 */
	public static void onScanOver() {
		// 延时播放，防止频道列表未储存完毕
//		new Handler().postDelayed(new Runnable() {
//			@Override
//			public void run() {
				MainActivity.createChannelList();
				ICast.startPlay();
//			}
//		}, 1000);
	}

	/**
	 * 打开CI菜单
	 */
	public static void showCiDialog() {
		MainActivity.showCiDialog();
	}

	/**
	 * 关闭CI菜单
	 */
	public static void closeCiDialog() {
		MainActivity.closeCiDialog();
	}

	/**
	 * 打开PIN菜单
	 */
	public static void showPinDialog() {
		MainActivity.showPinDialog();
	}

	/**
	 * 关闭PIN菜单
	 */
	public static void closePinDialog() {
		MainActivity.closePinDialog();
	}

	/**************************************** 播放器操作 ****************************************/

	private static MediaPlayer player;
	private static SurfaceView surfaceview;
	private static SurfaceHolder surfaceholder;

	/**
	 * 设置播放器surfaceView，该方法须由Activiy调用
	 */
	public static void setSurfaceView(SurfaceView surfaceView) {
		surfaceview = surfaceView;
		surfaceholder = surfaceview.getHolder();
	}

	public static void startPlayer() {
		try {
			if (player == null) {
				player = SmitPlayer.getPlayer();
				player.setDisplay(surfaceholder);
			}
			player.reset();
			SmitPlayer.updateDataSource();
			player.setLooping(true);
			player.setOnPreparedListener(new OnPreparedListener() {
				@Override
				public void onPrepared(MediaPlayer mp) {
					player.start();
				}
			});
			player.prepareAsync();
		} catch (Exception e) {
			LogCat.log("startPlayer error = " + e);
		}
	}

	public static void stopPlayer() {
		if (player != null) {
			player.stop();
		}
	}

	public static void resetPlayer() {
		if (player != null) {
			player.reset();
		}
	}
}
